<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>添加模块</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/js/layui/css/layui.css" media="all">
    <style type="text/css">
        .uploader-list {
            margin-left: -15px;
        }

        .uploader-list .info {
            position: relative;
            margin-top: -25px;
            background-color: black;
            color: white;
            filter: alpha(Opacity=80);
            -moz-opacity: 0.5;
            opacity: 0.5;
            width: 200px;
            height: 25px;
            text-align: center;
            display: none;
        }

        .uploader-list .handle {
            position: relative;
            background-color: black;
            color: white;
            filter: alpha(Opacity=80);
            -moz-opacity: 0.5;
            opacity: 0.5;
            width: 200px;
            text-align: right;
            height: 18px;
            margin-bottom: -18px;
            display: none;
        }

        .uploader-list .handle i {
            margin-right: 5px;
        }

        .uploader-list .handle i:hover {
            cursor: pointer;
        }

        .uploader-list .file-iteme {
            margin: 12px 0 0 15px;
            padding: 1px;
            float: left;
        }
    </style>
    <script src="../js/verify.js"></script>
</head>
<body>
<div style="width:80%;margin:15px auto;" id="aaa">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">所属分类</label>
            <div class="layui-input-block">
                <input type="text" name="parentName" id="parentName" required disabled  lay-verify="required" placeholder="请输入模块名称" autocomplete="off" class="layui-input layui-disabled">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">模块名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" id="name" required  lay-verify="required" placeholder="请输入模块名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">内容类型</label>
            <div class="layui-input-block">
                <select lay-verify="required" disabled lay-search id="contentType" name="contentType" lay-filter="contentType">
                    <option value="img">图片</option>
                    <option value="text">文本</option>
                    <option value="imgAndText" selected>图片+文本</option>
                </select>
            </div>
        </div>

        <div class="layui-upload" style="display: none;">
            <label class="layui-form-label">客户端显示</label>
            <div class="layui-input-block">
                <input type="checkbox" id="isShowApp" checked name="isShowApp" value="1" title="显示到H5页面">
                <input type="checkbox" id="isShowWeb" name="isShowWeb" value="0" title="显示到Web端">
            </div>
        </div>

<!--        <div class="layui-form-item">-->
<!--            <label class="layui-form-label">状态</label>-->
<!--            <div class="layui-input-block">-->
<!--                <select lay-verify="required" lay-search id="status" name="status">-->
<!--                    <option value="1">启用</option>-->
<!--                    <option value="0">禁用</option>-->
<!--                </select>-->
<!--            </div>-->
<!--        </div>-->

        <div class="layui-form-item">
            <label class="layui-form-label">模块介绍</label>
            <div class="layui-input-block">
                <input type="text" name="introduce" id="introduce" placeholder="请输入模块名称" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div id="from_div">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend>模块内容</legend>
            </fieldset>
            <div class="layui-card">
                <!-- 图片div -->
                <div class="layui-upload" id="imgs">
                    <div style="margin-left: 30px;">
                        <button type="button" class="layui-btn" id="test2">图片上传(可多选)</button>
                    </div>
                    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                        预览图：
                        <div class="layui-upload-list uploader-list" style="overflow: auto;" id="uploader-list"></div>
                        <input type="hidden" class="input-text" id="logo" name="content">
                    </blockquote>
                </div>

                <!-- 文本div -->
                <div id="texts">
                    <label class="layui-form-label">内容</label>
                    <div class="layui-input-block">
                        <script id="editor_tai" type="textain" style="height: 200px;width:98%;margin: auto"></script>
                    </div>
                </div>

                <div class="layui-card">
                    <!-- 图片+文本div -->
                    <div class="layui-card-body layui-text" id="imgText">
                        <table id="dataTable" lay-filter="dataTable" class="layui-hide"></table>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-form-item" style="margin-top: 20px">
            <div class="layui-input-block">
                <button class="layui-btn" id="addModule" lay-submit lay-filter="addModule">立即添加</button>
                <button type="reset" id="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>


<script type="text/html" id="tb">
    <div class="layui-container" style="margin-left:0px;">
        <a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-addition"></i>新增内容</a>
    </div>
</script>

<script type="text/html" id="stu-toolbar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<script src="/js/layui/layui.all.js"></script>
<script src="/js/ueditor/1.4.3/ueditor.config.js" type="text/javascript" charset="utf-8"></script>
<script src="/js/ueditor/1.4.3/ueditor.all.js" type="text/javascript" charset="utf-8"></script>
<script src="/admin/js/token.js"></script>

<script>

    //url 传参
    function GetQueryString(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var a = decodeURI(decodeURI(window.location.search));
        var r = a.substr(1).match(reg);//search,查询？后面的参数，并匹配正则
        if(r!=null)return  unescape(r[2]); return null;
    }

    var fileNames = [];
    var ue = UE.getEditor('editor_tai');

    window.onload = function(){
        var $ = layui.jquery
        var parentName = GetQueryString("parentName");
        $("input[name='parentName']").val(parentName);
        $("#texts").hide();
        $("#imgText").show();
        $("#imgs").hide();
    }

    function previewImg(obj) {
        var img = new Image();
        img.src = obj.src;
        //var height = img.height + 50; // 原图片大小
        //var width = img.width; //原图片大小
        var imgHtml = "<img src='" + obj.src + "' width='800px' height='500px'/>";
        //弹出层
        layer.open({
            type: 1,
            shade: 0.8,
            offset: 'auto',
            area: [800 + 'px', 550 + 'px'],// area: [width + 'px',height+'px'],  //原图显示
            shadeClose: true,
            scrollbar: false,
            title: "图片预览", //不显示标题
            content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            cancel: function () {
                //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
            }
        });
    }

    var tableData = [];

    layui.use(['form' , 'jquery' , 'upload', 'layedit', 'table'], function(){
        var form = layui.form;
        var $ = layui.jquery;
        var upload = layui.upload;
        var table = layui.table;


        form.on('select(contentType)', function(data){
            if (data.value == "img") {
                $("#texts").hide();
                $("#imgText").hide();
                $("#imgs").show();
            }else if (data.value == "text") {
                $("#texts").show();
                $("#imgText").hide();
                $("#imgs").hide();
            }else {
                $("#texts").hide();
                $("#imgText").show();
                $("#imgs").hide();
            }
        });

        //修改操作
        form.on('submit(addModule)',function(data){
            data.field.contentType = $("#contentType").find("option:selected").text();
            if (data.field.contentType == "文本") {
                if (ue.getContent() == null || ue.getContent() == "" || ue.getContent() == undefined) {
                    layer.msg('模块内容不能为空');
                    return false;
                }
                data.field.content = ue.getContent();
            }else if (data.field.contentType == "图片") {
                if (fileNames.length <= 0) {
                    layer.msg('模块内容不能为空');
                    return false;
                }
                data.field.contentList = fileNames;
            }else {
                var dataTable = layui.table.cache['data_table'];
                if (dataTable.length <= 0) {
                    layer.msg('模块内容不能为空');
                    return false;
                }
                data.field.contentImgTextList = dataTable;
            }
            if ($("#isShowApp").prop("checked")) {
                data.field.isShowApp = 1;
            }else {
                data.field.isShowApp = 0;
            }
            if ($("#isShowWeb").prop("checked")) {
                data.field.isShowWeb = 1;
            }else {
                data.field.isShowWeb = 0;
            }
            data.field.name =  replaceReg(data.field.name);  // 替换
            $.ajax({
                url: "/module/addModule"
                ,type:"POST"
                ,contentType: 'application/json'
                ,data:JSON.stringify(data.field)
                , success: function (data) {
                    if(data.code==500) {
                        layer.msg(data.msg);
                    }else if(data.code==200){
                        layer.close(layer.index);
                        layer.msg('添加成功');
                        setTimeout(function(){
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);//关闭弹出层
                            parent.location.reload();//重新加载父页面表格
                        }, 2000);
                    }else {
                        layer.msg('拒绝访问');
                    }
                }
                , error: function () {
                    console.log("ajax error");
                }
            });
            return false;
        });

        //多图片上传
        var uploadInst = upload.render({
            elem: '#test2'
            ,url: '/upload' //此处配置你自己的上传接口即可
            ,multiple: true
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){

                });
            }
            , done: function (res) {
                //判断上传是否成功
                if (res.code == 0) {
                    fileNames.push(res.data);
                    var index2 = layui.layer.load();
                    layer.close(index2);

                    $('#uploader-list').append(
                        '<div id="" class="file-iteme">' +
                        '<div class="handle" data-index="'+res.data+'"><i class="layui-icon layui-icon-delete" data-index="'+res.data+'"></i></div>' +
                        '<img style="width: 200px;height: 150px;" src='+ "/tmp/" + res.data +' class="layui-upload-img">' +
                        '</div>'
                    );
                    return layer.msg('上传成功！');
                }else{
                    var index = layui.layer.load();
                    layer.close(index);
                    return layer.msg('上传失败！');
                }
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #ff5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        $(document).on("mouseenter mouseleave", ".file-iteme", function(event){
            if(event.type === "mouseenter"){
                //鼠标悬浮
                $(this).children(".info").fadeIn("fast");
                $(this).children(".handle").fadeIn("fast");
            }else if(event.type === "mouseleave") {
                //鼠标离开
                $(this).children(".info").hide();
                $(this).children(".handle").hide();
            }
        });

        // 删除图片
        $(document).on("click", ".file-iteme .handle", function(event){
            $(this).parent().remove();
            var index = fileNames.indexOf($(this).attr("data-index"));
            fileNames.splice(index,1);
        });

        var mId = $("#id").val();
        table.render({
            elem: '#dataTable',
            id: "data_table",
            data: tableData,
            toolbar: '#tb',
            cols: [[
                {field: 'id',title: '序号',type:'numbers',align: 'center'},
                {field: 'title',align : 'center', title: '标题'},
                {field: 'content',align : 'center', title: '图片',templet: function (d) {
                    if(d.content.startsWith("/tmp/"))
                        return  '<div><img src="'+d.content+'" style="width: 70px;height: 50px;" onclick="previewImg(this)"></div>';
                    else
                        return '<div><img src="/upload/'+d.content +'" style="width: 70px;height: 50px;" onclick="previewImg(this)"></div>';
                    }},
                {field: 'description',align : 'center', title: '描述'},
                {toolbar: "#stu-toolbar",align : 'center', title: "操作" , fixed:"right"}
            ]]
            , page: true
            ,page: {
                curr: layui.data("content_page").index
            },
            done: (res, curr, count) => {
                layui.data("content_page", {
                    key: 'index',
                    value: curr
                });
            }
        });

        table.on('toolbar(dataTable)', function (obj) {
            var mId = $("#id").val();
            if (obj.event === 'add') {
                layer.open({
                    type: 2
                    ,title: "添加模块内容"
                    ,skin: 'layui-layer-molv'
                    ,area: ['95%', '85%']
                    ,content: (encodeURI("add_img_text.html?mId=" + mId)) //这里content是一个普通的String
                    ,end: function() {
                        //刷新页面,
                        table.reload('data_table', {data: tableData});
                    }
                });
            }
        });

        table.on('tool(dataTable)', function (obj) {
            if (obj.event === 'del') {
                layer.confirm("确定要删除吗？",{btn:['确定','取消']},
                    function(){
                        tableData.splice(obj.tr.data('index'),1);
                        layer.msg("删除成功",{time: 10},function(){
                            table.reload('data_table',{data : tableData});
                        });
                    }
                )
            }
        });
    });

    function getTableData(tableRow) {
        tableData.push(tableRow);
    }
</script>
</body>
</html>